﻿using System;
using System.Linq;
using System.Web.Mvc;
using InvoiceInvoker.Logic;
using InvoiceInvoker.Logic.Repositories;
using InvoiceInvoker.MvcUI.Helpers;
using InvoiceInvoker.MvcUI.Models;
using InvoiceInvoker.MvcUI.ViewModels;
using InvoiceInvoker.MvcUI.Filters;

namespace InvoiceInvoker.MvcUI.Controllers
{
	[Authorize]
	[HandleError]
	public class CustomersController : Controller
	{
		private int _sellerId;
		private RegisteredCustomerRepository _repository;

		protected override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			this.SetSellerId();
			_sellerId = (int)Session["SellerId"];
			_repository = new RegisteredCustomerRepository(_sellerId);

			base.OnActionExecuting(filterContext);
		}

		//
		// GET: /Customers/

		public ActionResult Index(CustomersIndexViewModel viewModel)
		{
			if (viewModel.Filter == null)
				viewModel.Filter = new CustomersFilter();

			viewModel.Customers = _repository.GetByExpression(viewModel.Filter.GetExpression());

			return View(viewModel);
		}

		//
		// GET: /Customers/Details/5

		public ActionResult Details(int id)
		{
			CustomerModel customer = new CustomerModel(_repository.GetById(id));

			return View(customer);
		}

		//
		// GET: /Customers/Create

		public ActionResult Create()
		{
			return View(new CustomerModel(_sellerId));
		}

		//
		// POST: /Customers/Create

		[HttpPost]
		public ActionResult Create(CustomerModel customer)
		{
			if (ModelState.IsValid)
			{
				_repository.Add(customer.ToRegisteredCustomer());

				return RedirectToAction("Index");
			}
			else
			{
				return View(customer);
			}
		}

		//
		// GET: /Customers/Edit/5

		public ActionResult Edit(int id)
		{
			CustomerModel customer = new CustomerModel(_repository.GetById(id));

			return View(customer);
		}

		//
		// POST: /Customers/Edit/5

		[HttpPost]
		public ActionResult Edit(int id, CustomerModel customer)
		{
			if (ModelState.IsValid)
			{
				_repository.Update(customer.ToRegisteredCustomer());

				return RedirectToAction("Index");
			}
			else
			{
				return View(customer);
			}
		}

		//
		// GET: /Customers/Delete/5

		public ActionResult Delete(int id)
		{
			CustomerModel customer = new CustomerModel(_repository.GetById(id));

			return View(customer);
		}

		//
		// POST: /Customers/Delete/5

		[HttpPost]
		public ActionResult Delete(int id, FormCollection collection)
		{
			_repository.Remove(id);

			return RedirectToAction("Index");
		}
	}
}
